use wasm_bindgen::prelude::*;

use pdfium_render::prelude::*;
use web_sys::{CanvasRenderingContext2d, HtmlCanvasElement, ImageData};

// 用于初始化PDFium
#[wasm_bindgen(start)]
pub fn start() {
    console_error_panic_hook::set_once(); // 捕获Rust中的panic并将其打印到JS控制台
}

#[wasm_bindgen]
pub async fn render_pdf_to_canvas(
    pdf_data: Vec<u8>,
    canvas_id: &str,
    page_number: u16,
) -> Result<(), JsValue> {
    // 获取浏览器窗口对象
    let window = web_sys::window().expect("no global `window` exists");
    let document = window.document().expect("should have a document on window");
    // 获取canvas元素
    let canvas = document.get_element_by_id(canvas_id).unwrap();
    let canvas: HtmlCanvasElement = canvas.dyn_into::<HtmlCanvasElement>()?;

    // 获取Canvas的2D上下文
    let context = canvas
        .get_context("2d")?
        .unwrap()
        .dyn_into::<CanvasRenderingContext2d>()?;

    // 初始化PDFium并加载PDF
    let binding = Pdfium::bind_to_system_library().unwrap();
    let pdfium = Pdfium::new(binding);
    let document = pdfium
        .load_pdf_from_byte_vec(pdf_data.clone(), None)
        .unwrap();
    // 确保页面号有效
    let page = document.pages().get(page_number).unwrap();

    // 获取PDF页面的宽高
    let width = page.width().value;
    let height = page.height().value;

    // 调整Canvas大小
    canvas.set_width(width as u32);
    canvas.set_height(height as u32);

    // 创建图像数据并渲染到Canvas
    let bitmap = page.render(width as i32, height as i32, None).unwrap();
    let image_data = bitmap.as_image().to_rgba8();
    let raw_pixels = image_data.into_raw();
    let img_data = ImageData::new_with_u8_clamped_array_and_sh(
        wasm_bindgen::Clamped(&raw_pixels),
        width as u32,
        height as u32,
    ).unwrap();
    context.put_image_data(&img_data, 0.0, 0.0)?;
    Ok(())
}
